﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace LeiDacceshi
{
	/*
     * 
     *  Writer:
     * 
     *  Date: 20230328
     * 
     *  Function:通过注册表让程序开机自启
     * 
     *  Remarks:  win+R打开运行。  输入   regedit  打开注册表，按照自己设置的_targetPath目标项路径依次打开，就可看到新建的键值
     * 
     */

	public static class Regeditkey
	{
		/// <summary>
		/// //获取当前进程
		/// </summary>
		public static string _path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
		/// <summary>
		/// 注册表中的名称
		/// </summary>
		//   public static string _nameInRegistry = "MyProject";
		/// <summary>
		/// 目标项路径
		/// </summary>
		public static string _targetPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

		/// <summary>
		/// 开机自启  
		/// </summary>
		/// <param name="registryname"></param>注册表中的名称
		public static void OnSetupStartupButtonClick(string registryname)
		{
			// 提示，需要更改注册表
			try
			{
				Microsoft.Win32.RegistryKey rgkRun = Get_RegistryKey(_targetPath);
				//设置键值
				rgkRun.SetValue(registryname, _path);
			}
			catch { Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); }
			finally { RegeditkeyDebugLog(registryname); }
		}


		/// <summary>
		/// 关闭自启
		/// </summary>
		public static void OnCancelStartupButtonClick(string registryname)
		{
			// 提示，需要更改注册表
			try
			{
				RegistryKey rgkRun = Get_RegistryKey(_targetPath);
				//删除键值
				rgkRun.DeleteValue(registryname, false);
			}
			catch { Console.WriteLine("Error!"); }
			finally { RegeditkeyDebugLog(registryname); }
		}


		/// <summary>
		/// 输出日志：自启动的状态
		/// </summary>
		public static void RegeditkeyDebugLog(string registryname)
		{
			RegistryKey rgkRun = Get_RegistryKey(_targetPath);
			//判断是否写入
			if (rgkRun.GetValue(registryname) == null) Console.WriteLine("自启动为关闭");
			else Console.WriteLine("自启动为打开");
		}


		/// <summary>
		/// 判断注册表文件项是否存在，不存在则创建
		/// </summary>
		/// <param name="_targetPath">目标路径</param>
		/// <returns></returns>
		public static RegistryKey Get_RegistryKey(string _targetPath)
		{
			RegistryKey rgkRun = Registry.CurrentUser.OpenSubKey(_targetPath, true);
			if (rgkRun == null)
			{
				rgkRun = Registry.CurrentUser.CreateSubKey(_targetPath);
			}
			return rgkRun;
		}
	}
}
